package com.eqdd.yiqidian.ui.chat;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.eqdd.yiqidian.ConversitionActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.base.DemoContext;
import com.eqdd.yiqidian.ui.MainActivity;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.ui.tongxunlu.TeamCheatInfoActivity;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.SPUtil;

import java.util.Locale;

import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

import static io.rong.imkit.utils.SystemUtils.getCurProcessName;


/**
 * Created by vzhihao on 2017/2/25.
 */
public class NewConversationActivity extends BaseActivity {
    private static final String BEIWANGLU = "转入备忘录";
    private static final String RENWU = "转入任务";
    private static final String COPY = "复制";
    private static final String DELIVER = "发送给朋友/同事";
    private static final String COLLECTION = "收藏";
    private static final String DELETE = "删除";
    private static final String RECALL = "撤回消息";
    private static final String TITLE = "易企点";
    public static final int SET_TEXT_TYPING_TITLE = 1;
    public static final int SET_VOICE_TYPING_TITLE = 2;
    public static final int SET_TARGETID_TITLE = 3;

    private String mTargetId;

    /**
     * 刚刚创建完讨论组后获得讨论组的id 为targetIds，需要根据 为targetIds 获取 targetId
     */
    private String mTargetIds;

    /**
     * 会话类型
     */
    private Conversation.ConversationType mConversationType;
    private String title;
    //    Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case SET_TEXT_TYPING_TITLE:
//                    dataBinding.includeTitle.tvTitle.setText("对方正在输入...");
//                    break;
//                case SET_VOICE_TYPING_TITLE:
//                    dataBinding.includeTitle.tvTitle.setText("对方正在说话...");
//                    break;
//                case SET_TARGETID_TITLE:
//                    dataBinding.includeTitle.tvTitle.setText(title);
//                    break;
//            }
//        }
//    };
    private ConversationFragment fragment;
    private ConversitionActivityCustom dataBinding;
    private String source;
    private String textContent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        super.onCreate(savedInstanceState);

    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_conversition);
        int density = (int) getResources().getDisplayMetrics().density;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(40 * density, 40 * density);
        dataBinding.includeTitle.ivRight.setLayoutParams(params);
    }

    @Override
    public void initData() {

    }

    @Override
    public void setView() {
        Intent intent = getIntent();

        getIntentData(intent);

        isReconnect(intent);
//        RongIMClient.setTypingStatusListener((type, targetId, typingStatusSet) -> {
//            //当输入状态的会话类型和targetID与当前会话一致时，才需要显示
//            if (type.equals(mConversationType) && targetId.equals(mTargetId)) {
//                //count表示当前会话中正在输入的用户数量，目前只支持单聊，所以判断大于0就可以给予显示了
//                int count = typingStatusSet.size();
//                if (count > 0) {
//                    Iterator iterator = typingStatusSet.iterator();
//                    TypingStatus status = (TypingStatus) iterator.next();
//                    String objectName = status.getTypingContentType();
//
//                    MessageTag textTag = TextMessage.class.getAnnotation(MessageTag.class);
//                    MessageTag voiceTag = VoiceMessage.class.getAnnotation(MessageTag.class);
//                    //匹配对方正在输入的是文本消息还是语音消息
//                    if (objectName.equals(textTag.value())) {
//                        //显示“对方正在输入”
//                        mHandler.sendEmptyMessage(SET_TEXT_TYPING_TITLE);
//                    } else if (objectName.equals(voiceTag.value())) {
//                        //显示"对方正在讲话"
//                        mHandler.sendEmptyMessage(SET_VOICE_TYPING_TITLE);
//                    }
//                } else {
//                    //当前会话没有用户正在输入，标题栏仍显示原来标题
//                    mHandler.sendEmptyMessage(SET_TARGETID_TITLE);
//                }
//            }
//        });

    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
    }

    private void getIntentData(Intent intent) {


        mTargetId = intent.getData().getQueryParameter("targetId");
        mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
        title = getIntent().getData().getQueryParameter("title");
//        source = mConversationType == Conversation.ConversationType.PRIVATE ? "私聊-" + title : "群组-" + title;
        initTopTitleBar(View.VISIBLE, title);
        enterFragment(mConversationType, mTargetId);
        if (mConversationType == Conversation.ConversationType.GROUP) {
            initTopRightImage(R.mipmap.talk_qun, v -> {
                Bundle bundle = new Bundle();
                bundle.putString("groupid", mTargetId);
                bundle.putString("groupname", title);
                startActivity(TeamCheatInfoActivity.class, bundle);
            });


        } else {
            initTopRightImage(R.mipmap.talk_person, v -> {
                Bundle bundle = new Bundle();
                bundle.putString(Config.GUID, mTargetId);
                startActivity(UserCardActivity.class, bundle);
            });
        }

    }


    /**
     * 加载会话页面 ConversationFragment
     *
     * @param mConversationType
     * @param mTargetId
     */

    private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {

        fragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation);

        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("conversation").appendPath(mConversationType.getName().toLowerCase())
                .appendQueryParameter("targetId", mTargetId).build();
        fragment.setUri(uri);
    }


    /**
     * 判断消息是否是 push 消息
     */
    private void isReconnect(Intent intent) {


        String token = null;

        if (DemoContext.getInstance() != null) {
            token = SPUtil.getToken(GreenDaoUtil.getUser().getUname());
        }

        //push或通知过来
        if (intent != null && intent.getData() != null && intent.getData().getScheme().equals("rong")) {

            //通过intent.getData().getQueryParameter("push") 为true，判断是否是push消息
            if (intent.getData().getQueryParameter("push") != null
                    && intent.getData().getQueryParameter("push").equals("true")) {

                reconnect(token);
            } else {
                //程序切到后台，收到消息后点击进入,会执行这里
                if (RongIM.getInstance() == null || RongIM.getInstance().getRongIMClient() == null) {

                    reconnect(token);
                } else {
                    enterFragment(mConversationType, mTargetId);
                }
            }
        }
    }


    /**
     * 重连
     *
     * @param token
     */
    private void reconnect(String token) {

        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String s) {

                    enterFragment(mConversationType, mTargetId);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }
}
